package com.leyou.sms.mq;

import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.utils.SmsUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

import static com.leyou.common.constants.MQConstants.Exchange.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.Queue.SMS_VERIFY_CODE_QUEUE;
import static com.leyou.common.constants.MQConstants.RoutingKey.VERIFY_CODE_KEY;


/**
 * 监听队列然后发送短信
 */
@Component
public class MessageListener {

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private SmsProperties prop;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name= SMS_VERIFY_CODE_QUEUE /*验证码队列*/ , durable = "true"), // 配置了队列的名称和持久化
            exchange = @Exchange(
                    name = SMS_EXCHANGE_NAME,   // 交换机名称
                    type = ExchangeTypes.TOPIC  //  类型
            ),
            key = VERIFY_CODE_KEY /*RoutingKEY*/
    ))
    public void sendSms(Map<String, String> msg){
        //判断消息是否为空
        if(CollectionUtils.isEmpty(msg)){
            return;
        }
        // 获取手机号
        String phone = msg.get("phone");
        if(!RegexUtils.isPhone(phone)){
            return;
        }
        // 获取验证码
        String code = msg.get("code");
        if(!RegexUtils.isVerifyCode(code)){
            return;
        }
        String param = "{\"code\":\""+code+"\"}";
        // 发送短信
        smsUtils.sendMessage(phone, prop.getSignName(), prop.getVerifyCodeTemplate(), param);
    }
}
